import numpy as np
import cv2 as cv
import time
import datetime

colour = ((0,205,205),(154,250,0),(34,34,178),(211,0,148),(255,118,72),(137,137,139))                        #定义矩形的颜色
videoFileName = r'vtest.avi'
cap = cv.VideoCapture(videoFileName)                                                                         #导入视频
fgbg = cv.createBackgroundSubtractorMOG2()                                                                   #混合高斯背景建模法

fourcc = cv.VideoWriter_fourcc(*'XVID')                                                                      #设置保存图片的格式
out = cv.VideoWriter(datetime.datetime.now().strftime("%A_%d_%B_%Y_%I_%M_%S%p")+'.avi',fourcc,10,(768,576))  #分辨率和原视频对应

while True:
    ret,frame = cap.read()                                                                                   #读取图片
    fgmask = fgbg.apply(frame)
    element = cv.getStructuringElement(cv.MORPH_CROSS,(3,3))                                                 #形态学去噪
    fgmask = cv.morphologyEx(fgmask,cv.MORPH_OPEN,element)                                                   #形态学滤波中的开运算去除噪声
    _,contours,hierarchy = cv.findContours(fgmask.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)            #寻找前景
    count = 0
    for cont in contours:
        Area = cv.contourArea(cont)                               #计算轮廓的面积
        if Area < 10:                                             #过滤面积小于10
            continue
        count += 1                                                #计数加1
        print("{}-prospect:{}".format(count,Area),end = " ")      #打印出每个前景的面积
        rect = cv.boundingRect(cont)                              #提取矩形的面积
        print("x:{} y:{}".format(rect[0],rect[1]))                #打印出坐标
        cv.rectangle(frame,(rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]),colour[count%6],1)            #在原图上绘制矩形
        cv.rectangle(fgmask, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]),(0xff,0xff,0xff),1)  #在黑白前景上绘制矩形

        y = 10 if rect[1] < 10 else rect[1]
        cv.putText(frame,str(count),(rect[0],y),cv.FONT_HERSHEY_COMPLEX,0.4,(0,255,0),1)                     #在前景上写编号

    cv.putText(frame,"count:",(5,20),cv.FONT_HERSHEY_COMPLEX,0.6,(0,255,0),1)                                #显示总数
    cv.putText(frame,str(count), (75, 20), cv.FONT_HERSHEY_COMPLEX, 0.6, (0, 255, 0), 1)
    print("...............................")

    cv.imshow('frame',frame)      #在原图上标注
    cv.imshow('frame2',fgmask)    #以黑白形式显示前景和背景
    out.write(frame)
    out.write(fgmask)
    k = cv.waitKey(30)&0xff
    if k == 27:
        break
out.release()                     #释放文件
cap.release()
cv.destroyAllWindows()